<template>
	<div class="yellow" style="position: fixed; left: 0; top: 0; z-index: 999; width: 100%; height: 100%;">
		<div class="header flex a-center jlr">
			<div class="back" @click="back"><i class="iconfont icon-arrow-left-copy"></i></div>
			<h2>个人信息</h2>
			<div class="back">&nbsp;</div>
		</div>
		<div style="padding-top: 0.92rem;">
			<div class="setting1">
				<div class="item flex jlr a-center">
					<h3>头像</h3>
					<div class="flex a-center" style="position: relative;">
						<input type="file" accept="image/*" @change="uploadImg($event)" style="opacity: 0; width: 100%; height: 100%; position: absolute; left: 0; top: 0; z-index: 3;">
						<div class="touxiang">
							<img :src="headImgUrl" >
						</div>
						<i class="iconfont icon-arrow-right"></i>
					</div>

				</div>
				<div class="item flex jlr a-center">
					<h3>昵称</h3>
					<div class="flex a-center" style="flex: 1;">
						<input type="text" v-model="username">
					</div>

				</div>
				<div class="item flex jlr a-center">
					<h3>性别</h3>
					<div class="isradio flex a-center">
						<van-radio-group v-model="radio">
						  <van-radio name="1" icon-size="20px" checked-color="#fe7537">男</van-radio>
						  <van-radio name="2" icon-size="20px" checked-color="#fe7537">女</van-radio>
						</van-radio-group>
					</div>

				</div>
			</div>


			<div style="text-align: center">
      <button class="blockbtn" style="border: none" @click="save()">保存</button>
      </div>

		</div>


	</div>
</template>
<script>
  import service from '@/util/service';
export default {
	data(){
		return {
      radio:'',
			username:'',
      headImgUrl: ''
		}
	},
  activated() {
    this.init()
  },
	methods:{
    init() {
      this.$ajax.getMemberInfo({
        memberId: this.$route.query.memberId
      }).then(res => {
        if (res.code == 0) {
          this.radio = String(res.data.sex);
          this.username = res.data.nickName;
          this.headImgUrl = res.data.headImgUrl
        }
      })
    },
    save : function() {
      this.$ajax.updateMemberInfo({
        memberId: this.$route.query.memberId,
        sex: this.radio,
        nickName: this.username,
        headImgUrl: this.headImgUrl
      }).then(res => {
        if (res.code == 0) {
          this.$toast({message: '个人信息设置成功', duration: 500});
          this.back();
        }
      })
    },
    f(res) {//上传图片
      this.$ajax.uploadImg({
        base64Str : res.img,
        imgType : res.imgType
      }).then(req => {
        if (req.code == 0) {
          this.headImgUrl = req.data.imgUrl
        }
        console.log(this.headImgUrl)
      })
    },
		file(e){
			this.$fn.uploadImg(e).then(res=>{
				console.log(res)//base 64 去头的和没有去头的都在这
        this.f(res)
			})
		},
    uploadImg(e){
      const that = this;
      // 利用fileReader对象获取file
      let file = e.target.files[0];
      let filename = file.name;
      let imgType = '';
      const suffixIndex = filename.lastIndexOf('.');
      if(suffixIndex > 0){
        imgType = filename.substring(suffixIndex + 1,filename.length);
        console.log('imgType :',imgType);
      }

      let img = new Image();
      let reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = function (e) {
        img.src = e.target.result;
        console.log('img length :',img.src.length);

        if(img.src.length > 500 * 1024){
          img.onload = function(){
            const compressData =  that.compress(img,imgType);
            console.log('compressData length :',compressData.length);
            that.doUploadImg(compressData,imgType);
          };
        }else{
          that.doUploadImg(img.src,imgType);
        }
      };

    },
    compress(img,imgType) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext('2d');
      //瓦片canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = width * height / 4000000) > 1) {
        console.log("大于400万像素")
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      //铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = width * height / 1000000) > 1) {
        console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
        //计算每块瓦片的宽和高
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      //进行最小压缩
      let ndata = canvas.toDataURL('image/jpeg', 0.3);
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
    doUploadImg(imgData,imgType){
      const that = this;
      const base64Str = imgData.split(",")[1];
      //alert('base64Str 1:'+imgData.split(",")[0]);
      //alert('base64Str 2:'+base64Str);

      const reqData = {
        base64Str: base64Str,
        imgType: '.' + imgType
      };
      this.$ajax.uploadImg(reqData).then(res => {
        if(res != null){
          const code = res.code;
          if(code == 0){
            const data = res.data;
            const imgUrl = data.imgUrl;
            if(imgUrl){
              that.headImgUrl = imgUrl;
            }
          }
        }
      });
    },
		back(){
			this.$router.go(-1)
		}
	}
}
</script>
